package com.server.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.oreilly.servlet.MultipartRequest;
import com.rqf.common.base.PathManager;
import com.server.common.util.NumberSystemUtil;
import com.server.date.DateUtil;

@Controller
@RequestMapping("file")
public class FileUploadController {
	private static DateFormat df = new SimpleDateFormat("yyyyMM");

	private static String tempPath = PathManager.FILE_SAVE_TEMP_PATH;

	// @Autowired
	// private ProjectInfo projectInfo;
	/*
	 * @Autowired private IAttchmntDetailService attchDetailService;
	 */

	/*
	 * @Autowired private IPrjImageDao prjImgDao;
	 * 
	 * @Autowired private IPrjProjectinfoDao projectInfoDao;
	 */

	@RequestMapping("page/{phoneNo}")
	public ModelAndView uploadPage(@PathVariable String phoneNo,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("common/fileupload");
		return mv;
	}

	@RequestMapping("upload/{phoneNo}")
	public void upload(@PathVariable String phoneNo,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		Boolean isSuccess = true;

		String base64Str = request.getParameter("base64");
		String[] split = base64Str.split("base64,");
		String tempStr = split[1];
		String realStr = tempStr.substring(0, tempStr.length()-3);
		//byte[] decode = FileUtil.base64Decode("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/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jcnUbUuD5ALFd6/Nx6jIH8qi2tjW+lzXtNSNqdkrb4j/CT0+lcH4vSAa7M9rLvjcAkYxsOPu1txaOIfESz4Waz2ZJlO9icYwQe+efSpPGGnpD4eFwIEhJuF2qqgcbW/8ArflVpWMZO/Qj8BeIre0jbTL1xErPuikY4GT1U+ld1NZW0/Lxrk9xwa8OrX0nxLqmkKEtrjdCP+WUg3L/AIj8KHElOx3GpWYDzWzg7GBAz6HpT9PtRLNHCq4jXrjjAFYB+IEssYFzpcErDuHIH8jR/wALBlijK2umQRMe5ckf0qeVmntNDv4rS3txuSNRjnceSPxrz3x74gg1F49Ps3EkML73kHRmxgAewyfzrE1XxHqmrgrdXJ8r/nkg2r+Xf8ayqpKxk3c//9k=");
		
	/*	byte[] decode = FileUtil.base64Decode(realStr);
		FileUtil.hex2Image(decode);*/

		/*String type = request.getParameter("type");
		if (StringUtils.isEmpty(type)) {
			type = "default";
		}
		String note = request.getParameter("note");
		String fileName = request.getParameter("fileName");
		// String filePath = projectInfo.getFilePath();//服务器文件地址
		String filePath = "C:\\Attachment\\lawyerPlatform";// 服务器文件地址
		filePath += "\\" + phoneNo + "\\" + type;
		String createDate = DateUtil.getDateWithSeconds(new Date());

		File directory = new File(filePath);
		if (!directory.exists()) {
			directory.mkdirs();
		}

		Date now = new Date();
		String saveDirectory = null;
		if (directory.exists()) {
			MultipartRequest multi = new MultipartRequest(request, filePath,
					100 * 1024 * 1024, "UTF-8");

			// 如果有上传文件, 则保存到数据内
			Enumeration files = multi.getFileNames();
			while (files.hasMoreElements()) {
				String name = (String) files.nextElement();
				File f = multi.getFile(name);
				if (f != null) {
					// 从临时文件夹重命名到指定文件夹
					String savepath = saveDirectory + "\\" + UUID.randomUUID();
					f.renameTo(new File(savepath));
					// response.getWriter().write(savepath); //可以返回一个JSON字符串,
					// 在客户端做更多处理
				}
			}
		}*/
	}

	/*
	 * @RequestMapping("/getUploadFile/{attchId}") public void
	 * getUploadFile(@PathVariable Integer attchId,HttpServletRequest request,
	 * HttpServletResponse response) throws IOException { AttchmntDetail
	 * attchModel = attchDetailService.get(attchId).getUnique();
	 * if(attchModel!=null){ String pathString = attchModel.getAddress();
	 * 
	 * File f = new File(pathString); if (!f.exists()) { throw new
	 * FileNotFoundException(pathString); }
	 * 
	 * ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
	 * BufferedInputStream in = null; try { in = new BufferedInputStream(new
	 * FileInputStream(f)); int buf_size = 1024; byte[] buffer = new
	 * byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0,
	 * buf_size))) { bos.write(buffer, 0, len); } byte[] data =
	 * bos.toByteArray(); String fileName =
	 * URLEncoder.encode(attchModel.getAttchmntName(), "UTF-8");
	 * response.reset(); response.setHeader("Content-Disposition",
	 * "attachment; filename=\"" + fileName + "\"");
	 * response.addHeader("Content-Length", "" + data.length);
	 * response.setContentType("application/octet-stream;charset=UTF-8");
	 * OutputStream outputStream = new BufferedOutputStream(
	 * response.getOutputStream()); outputStream.write(data);
	 * outputStream.flush(); outputStream.close(); } catch (IOException e) {
	 * e.printStackTrace(); } finally { try { in.close(); } catch (IOException
	 * e) { e.printStackTrace(); } bos.close(); } } }
	 */

	@RequestMapping("picDown/{phoneNo}")
	public void picDown(@PathVariable String phoneNo,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// PrjImage prjImage = prjImgDao.get(id);
		if (/* prjImage!=null */true) {
			/*
			 * String pathString = prjImage.getFilePath(); String realFileName =
			 * prjImage.getImageName();
			 */
			String pathString = "";
			String realFileName = "";

			File f = new File(pathString);
			if (!f.exists()) {
				pathString = request
						.getRealPath("/WEB-INF/resources/share/img/check.png");
				realFileName = "emptyImg.png";
				f = new File(pathString);
			}

			ByteArrayOutputStream bos = new ByteArrayOutputStream(
					(int) f.length());
			BufferedInputStream in = null;
			try {
				in = new BufferedInputStream(new FileInputStream(f));
				int buf_size = 1024;
				byte[] buffer = new byte[buf_size];
				int len = 0;
				while (-1 != (len = in.read(buffer, 0, buf_size))) {
					bos.write(buffer, 0, len);
				}
				byte[] data = bos.toByteArray();
				String fileName = URLEncoder.encode(realFileName, "UTF-8");
				response.reset();
				response.setHeader("Content-Disposition",
						"attachment; filename=\"" + fileName + "\"");
				response.addHeader("Content-Length", "" + data.length);
				response.setContentType("application/octet-stream;charset=UTF-8");
				OutputStream outputStream = new BufferedOutputStream(
						response.getOutputStream());
				outputStream.write(data);
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				bos.close();
			}
		}
	}

	/*
	 * @RequestMapping("/getOrgImg/{id}") public void getOrgImg(@PathVariable
	 * Integer id,HttpServletRequest request, HttpServletResponse response)
	 * throws IOException { String pathString = null; String fileRealName =
	 * "emptyOrgImg.png"; if(id==-1){ String emptyPicPath =
	 * "/WEB-INF/resources/share/img/emptyOrgImg.png"; pathString =
	 * request.getRealPath(emptyPicPath); fileRealName = "accept.png"; }else{
	 * PrjProjectinfo projectInfo = projectInfoDao.get(id);
	 * if(projectInfo!=null){ pathString = projectInfo.getOrgImgPath();
	 * fileRealName = projectInfo.getOrgImgName(); } }
	 * if(pathString==null)return;
	 * 
	 * File f = new File(pathString); if (!f.exists()) { throw new
	 * FileNotFoundException(pathString); }
	 * 
	 * ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
	 * BufferedInputStream in = null; try { in = new BufferedInputStream(new
	 * FileInputStream(f)); int buf_size = 1024; byte[] buffer = new
	 * byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0,
	 * buf_size))) { bos.write(buffer, 0, len); } byte[] data =
	 * bos.toByteArray(); String fileName = URLEncoder.encode(fileRealName,
	 * "UTF-8"); response.reset(); response.setHeader("Content-Disposition",
	 * "attachment; filename=\"" + fileName + "\"");
	 * response.addHeader("Content-Length", "" + data.length);
	 * response.setContentType("application/octet-stream;charset=UTF-8");
	 * OutputStream outputStream = new BufferedOutputStream(
	 * response.getOutputStream()); outputStream.write(data);
	 * outputStream.flush(); outputStream.close(); } catch (IOException e) {
	 * e.printStackTrace(); } finally { try { in.close(); } catch (IOException
	 * e) { e.printStackTrace(); } bos.close(); } }
	 */
}
